package com.jxwifi.cloud.quickclean.order;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.RouteSearch;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickclean.app.AccountMgr;
import com.jxwifi.cloud.quickclean.app.PasswordLogin;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.bean.InfoBean;
import com.jxwifi.cloud.quickclean.bean.MyCleanersBean;
import com.jxwifi.cloud.quickclean.bean.PayParamsBean;
import com.jxwifi.cloud.quickclean.bean.PriceDetailBean;
import com.jxwifi.cloud.quickclean.bean.ProductInfoVoBean;
import com.jxwifi.cloud.quickclean.bean.QuickTreBean;
import com.jxwifi.cloud.quickclean.bean.SystemBean;
import com.jxwifi.cloud.quickclean.bean.UcCustomerBank;
import com.jxwifi.cloud.quickclean.main.PriceExplainActivity;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.pay.PayResult;
import com.jxwifi.cloud.quickclean.pay.PayUtil;
import com.jxwifi.cloud.quickclean.pay.WxpayParams;
import com.jxwifi.cloud.quickclean.popwindow.PopAreaModule;
import com.jxwifi.cloud.quickclean.popwindow.PopPayDepositModule;
import com.jxwifi.cloud.quickclean.popwindow.PopPayModule;
import com.jxwifi.cloud.quickclean.popwindow.PopPayOrderModule;
import com.jxwifi.cloud.quickclean.popwindow.PopSexModule;
import com.jxwifi.cloud.quickclean.popwindow.PopTimeChoiceModule;
import com.popwindow.PopWindowUtil;
import com.popwindow.Popwindows;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.simple.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import cn.trinea.android.common.util.ListUtils;
import cn.trinea.android.common.util.REPattern;
import retrofit2.http.PUT;

public class ConfirmOrderPresenter {

    private String TAG = this.getClass().getSimpleName();
    private ConfirmOrderView mView;
    private Context mContext;
    private AuzImpl mAuz;

    private int mStartsTime = 8; //开始时间
    private int mTimeInterval = 1;//时间间隔
    private int mEndTime = 18;//结束时间

    private int mAreaindex = 0;//面积选择后默认状态标识
    private String mSpeceCode;//产品标签编号
    private String mProductPriceCode;//产品定价编号

    private double mTotalAmount ;//快洁宝用户余额
    private String mStarts;//余额状态
    private int mPageIndex = 1;
    private int mTotalNum;//记录接口中的总条数（如果没有返回这个字段也可以不适用）
    public List<MyCleanersBean> mrecords;


    public ConfirmOrderPresenter(Context context, ConfirmOrderView view) {
        this.mContext = context;
        this.mView = view;
        mAuz = new AuzImpl();
    }

    //初始化默认时间
    public void getTimeNow() {
        SimpleDateFormat sdfday = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        now.set(Calendar.HOUR_OF_DAY, now.get(Calendar.HOUR_OF_DAY) + mTimeInterval);
        now.set(Calendar.MINUTE, now.get(Calendar.MINUTE) + 5);
        if (now.get(Calendar.HOUR_OF_DAY) >= mEndTime) {
            SimpleDateFormat sdfday1 = new SimpleDateFormat("yyyy-MM-dd");
            Calendar now1 = Calendar.getInstance();
            now1.setTime(new Date());
            now1.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            mView.getConOrderTime().setText(sdfday1.format(now1.getTime()) +"  "+ mStartsTime + ":00");
        } else {
            //now.set(Calendar.MINUTE, now.get(Calendar.MINUTE) + 5);
            mView.getConOrderTime().setText(sdfday.format(now.getTime()));
        }
    }

    public void getOrderTime() {
        Params params = new Params();
        mAuz.auzget(UrlPool.SYSTEM_LIST, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) { //正常数据
                    List<SystemBean> msystemBean = JSON.parseArray(data, SystemBean.class);
                    for (int i = 0; i < msystemBean.size(); i++) {
                        if ("kjb_order_time_range".equals(msystemBean.get(i).getKeyName())) {
                            String[] mCustomer = msystemBean.get(i).getKeyValue().split(",");
                            String[] StartsTimeStr = mCustomer[0].split(":");
                            String[] EndTimeStr = mCustomer[1].split(":");
                            mStartsTime = Integer.valueOf(StartsTimeStr[0]);
                            mEndTime = Integer.valueOf(EndTimeStr[0]);
                            break;
                        }
                    }
                }
                getTimeNow();
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
                getTimeNow();
            }
        });
    }

    public void initView() {
        if (!ListUtils.isEmpty(mView.getProductsBean().getTags())) {
            mView.getField().setText("场地:" + mView.getProductsBean().getTags().get(0).getArea());
            mView.getMoney().setText(mView.getProductsBean().getTags().get(0).getDescription());
            //Log.i(TAG,"initView ==> description = "+mView.getProductsBean().getTags().get(0).getDescription());
            mView.getUnitPrice().setText(mView.getProductsBean().getServicePrice().getPrice()+"元/小时");
            mSpeceCode = mView.getProductsBean().getTags().get(0).getSpeceCode();
            mProductPriceCode = mView.getProductsBean().getServicePrice().getProductPriceCode();
        }
    }

    //服务面积选择
    public void MeasureService() {
        if (mView.getProductsBean() != null) {
            if (!ListUtils.isEmpty(mView.getProductsBean().getTags())) {
                PopAreaModule mCityModule = new PopAreaModule(mContext, mView.getProductsBean().getTags(), mAreaindex, new PopAreaModule.PopAreaListener() {
                    @Override
                    public void AreaClickTv(int position) {
                        mAreaindex = position;
                        mView.getField().setText("场地:" + mView.getProductsBean().getTags().get(position).getArea());
                        mView.getMoney().setText(mView.getProductsBean().getTags().get(position).getDescription());
                        //Log.i(TAG,"description = "+mView.getProductsBean().getTags().get(position).getDescription());
                        //mView.onEstimate(mProductsBean.get(mTagsPos).getDefaultPrice() * mProductsBean.get(mTagsPos).getTags().get(position).getHours());
                        mSpeceCode = mView.getProductsBean().getTags().get(position).getSpeceCode();
                        mProductPriceCode = mView.getProductsBean().getServicePrice().getProductPriceCode();
                        //Available();
                    }

                });
                Popwindows popwindow = PopWindowUtil.getPopupWindow(mCityModule.getView(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                        .LayoutParams.MATCH_PARENT);
                mCityModule.setPopwindow(popwindow);
                popwindow.show(mView.getField(), Popwindows.Location.BOTTOM);
            }
        }
    }

    //服务详情
    public void ProductDetails() {

        Intent intent = new Intent();
        intent.setClass(mContext, ProductDetailsActivity.class);
        intent.putExtra("product_code", mView.getProductsBean().getServicePrice().getProductCode());
        intent.putExtra("product_price_code", mView.getProductsBean().getServicePrice().getProductPriceCode());
        mContext.startActivity(intent);
    }

    //时间选择
    public void TimeChoice() {
        PopTimeChoiceModule mPopModule = new PopTimeChoiceModule(mContext, mStartsTime, mTimeInterval, mEndTime, new PopTimeChoiceModule.PopTiemListener() {
            @Override
            public void Determine(String OrderTime) {
                mView.getConOrderTime().setText(OrderTime);
            }
        });
        Popwindows window = PopWindowUtil.getPopupWindow(mPopModule.getView(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.MATCH_PARENT);
        mPopModule.setPopwindow(window);
        window.show(mView.getConOrderTime(), Popwindows.Location.TOP);
    }

    //费用说明接口
    public void priceDetail() {
        Params params = new Params();
        params.add("productPriceCode", mProductPriceCode);
        params.add("tagCode", mSpeceCode);
        mAuz.auzpost(UrlPool.POST_PRICE_DETAIL, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    PriceDetailBean mBean = JSON.parseObject(data, PriceDetailBean.class);
                    Intent intent = new Intent();
                    intent.setClass(mContext, PriceExplainActivity.class);
                    intent.putExtra("defaultprice", mBean.getPredictPrice());
                    intent.putExtra("hours", mBean.getHource());
                    intent.putExtra("estimatemoney", mBean.getDeposit());
                    intent.putExtra("costdescription", mBean.getAreaSize());
                    mContext.startActivity(intent);
                } else {
                    mView.onpriceDetail();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    //点击支付按钮的判断条件
    public void ifPayDeposit() {
        if (TextUtils.isEmpty(mView.getConOrderPhoneName().getText().toString())) {
            Toaster.show(mContext, "联系人不能为空");
            return;
        }
        if (mView.getConOrderPhone().getText().toString().equals("")) {
            Toaster.show(mContext, "手机号码不能为空");
            return;
        }
        boolean isMobile = REPattern.isMobileNO(mView.getConOrderPhone().getText().toString());
        if (!isMobile) {
            Toaster.show(mContext, "请输入正确的手机号码");
            return;
        }
        findbank();
    }

    //支付布局
    public void getPayOrder() {
        PopPayModule mPopPayOrder = new PopPayModule(mContext,Double.valueOf(mView.getProductPrice()),mTotalAmount,mStarts,"订金",mView.getResVoBean(), new PopPayModule.PopPayListener() {
            @Override
            public void getPayOrder(String PayType, String PayPrice) {
                onprepay(PayType);
            }
        });
        Popwindows window = PopWindowUtil.getPopupWindow(mPopPayOrder.getView(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.MATCH_PARENT);
        mPopPayOrder.setPopwindow(window);
        window.show(mView.getConOrderTime(), Popwindows.Location.TOP);
    }

    public void onprepay(String PayType) {
        Params params = new Params();
        params.add("dispatchType", mView.getdispatchType());//(选填)派单类型:SYS 系统派单 Appoint：指定. 默认为SYS
        if (StateUtils.APPOINT.equals(mView.getdispatchType())) {
            params.add("cleanerCode", mView.getCleaningCode());// 保洁员编号，派单类型为指定保洁员的需要必填
        }
        if (!TextUtils.isEmpty(mView.getResVoBean().getAssembleOrderCode())){
            params.add("assembleOrderCode", mView.getResVoBean().getAssembleOrderCode());//拼团编码
        }
        params.add("orderCode", mView.getResVoBean().getOrderCode());//订单code编码
        params.add("payChannelEnum", PayType);//支付渠道枚举，支付渠道枚举为支付的必填项；0：支付宝支付 1；目前只支持【支付宝支付,微信支付】两种
        params.add("remark", mView.getConOrderRemarksText().getText().toString());//备注
        params.add("serviceTime", mView.getConOrderTime().getText().toString());//服务开始时间
        params.add("tradeType", "2");//交易类型枚举，交易类型枚举为支付的需要必填；0： JSAPI 2：APP ，目前只支持【JSAPI,APP】两种
        params.add("userName", mView.getConOrderPhoneName().getText().toString());//联系人
        params.add("userTell", mView.getConOrderPhone().getText().toString());//联系电话
        params.add("productPriceCode", mProductPriceCode);
        params.add("tagCode", mSpeceCode);
        mAuz.auzpost(UrlPool.POST_PAY_v2_PREPAY, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                PayParamsBean mParams = JSON.parseObject(data, PayParamsBean.class);
                if (mParams.isNoPayment()){
                    EventBus.getDefault().post(new PayResult(true, mParams.getOutTradNo()), "e-PayResult");
                }else{
                    if (StateUtils.PAY_ALI.equals(mParams.getPayChannelEnum())) { //支付宝
                        PayUtil.getInstance().aliPay(mContext, mParams);
                    } else if (StateUtils.PAY_WX.equals(mParams.getPayChannelEnum())) { //微信
                        mView.getWXPayCode(mParams.getOutTradNo());
                        //mWXPay(mParams.getWxPayResult());
                        PayUtil.getInstance().WXPay(mContext, mParams.getWxPayResult());
                    }
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    //获取用户余额
    public void findbank(){
        mAuz.auzpost(UrlPool.POST_BANK_FINDBANK, new Params(), new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                UcCustomerBank mBean = JSON.parseObject(data, UcCustomerBank.class);
                if (mBean!=null){
                    mTotalAmount=Double.valueOf(mBean.getSurplusAmount());
                    mStarts=mBean.getStatus();
                }else{
                    mTotalAmount=0.0;
                    mStarts=StateUtils.NORMAL;
                }
                getPayOrder();
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
                getPayOrder();
            }
        });
    }

    //用户信息 用户获取默认地址信息
    public void getinfo() {
        Params params = new Params();
        params.add("customerCode", AccountMgr.getCode(mContext));
        mAuz.auzget(UrlPool.GET_INFO, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    InfoBean minfoBean = JSON.parseObject(data, InfoBean.class);
                    AccountMgr.putUser(mContext, minfoBean, true);
                    mView.onAddressBean(minfoBean.getDefaultAddress());
                } else {
                    mView.oninfo();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });

    }

    /**
     * 收藏保洁员列表
     */
    public void getCollectionCleanerData() {
        Params params = new Params();
        params.add("limit", mView.getLimit());
        params.add("orderCode", mView.getOrderCode());
        params.add("page", mPageIndex);
        params.add("serviceTime", mView.getServiceTime());
        params.add("likeWrapper", "");
        Log.i(TAG,"getCollectionCleanerData ==> ");
        mAuz.auzpost(UrlPool.POST_OLLECTION_CLEANER_LIST, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    JSONObject obj = JSON.parseObject(data);
                    String str = obj.getString("records");
                    mTotalNum = obj.getInteger("total");
                    mrecords = JSON.parseArray(str, MyCleanersBean.class);

                    Log.i(TAG,"onRideRouteSearched ==>0 收藏保洁员size：" + mrecords.size());
                    if(mrecords.size() < 1 ){
                        mView.setButtonGone();
                    }

                } else {
                    //mView.onData();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                ///mView.onFailure(errorCode, msg);
            }
        });
    }

}
